package eafit.sicom.calculadorapromedios;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;

import com.actionbarsherlock.app.SherlockActivity;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuInflater;
import com.actionbarsherlock.view.MenuItem;

public class MainActivity extends SherlockActivity {

	ListView listView;

	List<GradePercentage> listGradePercentage;

	GradePercentageAdapter adapter;

	TextView textViewMessage;

	private static final int GRADE_PERCENTAGE_SELECTED = 0;
	private static final int GRADE_DESIRED = 1;
	private static final int CONFIRM_DELETE = 2;
	public static final String MISSING_PERCENTAGE = "missingPercentage";

	public Double desiredGrade = 3.0;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		listGradePercentage = new ArrayList<GradePercentage>();
		textViewMessage = (TextView) findViewById(R.id.textViewMessage);

		// SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
		// String dg = settings.getString("desiredGrade", "3.0");
		// desiredGrade = Double.valueOf(dg);

		calcutateGrade();

		adapter = new GradePercentageAdapter(this);
		listView = (ListView) findViewById(R.id.mylist);

		listView.setAdapter(adapter);

		listView.setOnItemLongClickListener(new OnItemLongClickListener() {

			public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
					int arg2, long arg3) {

				listGradePercentage.remove(arg2);
				adapter.notifyDataSetChanged();
				calcutateGrade();
				return false;
			}
		});

	}

	public void calcutateGrade() {

		Double totalGrades = 0.0;
		Double totalPercentage = 0.0;
		for (GradePercentage gradePercetage : listGradePercentage) {
			totalGrades += (gradePercetage.getGrade()
					* (gradePercetage).getPercentage() / 100);
			totalPercentage += gradePercetage.getPercentage() / 100;
		}

		// Here we control that the total of percentage entered is not equal to
		// 1, to avoid division by 0
		Double gradeNeeded = 0.0;
		if (totalPercentage < 1) {
			gradeNeeded = (desiredGrade - totalGrades) / (1 - totalPercentage);
		} else {
			gradeNeeded = (desiredGrade - totalGrades);
		}
		showCalculateGrade(gradeNeeded, (1 - totalPercentage));
	}

	public void showCalculateGrade(Double grade, Double percentage) {
		DecimalFormat df = new DecimalFormat();
		df.setMinimumFractionDigits(2);
		df.setMaximumFractionDigits(2);
		String gradeNeeded = String.valueOf(df.format(grade));
		//Comentario y ya
		String percentageNeeded= String.valueOf((df.format(percentage * 100.0 )));
		
		String message = String.format(getString(R.string.you_x_need_in_y), gradeNeeded,percentageNeeded);

		textViewMessage.setText(message);
	}
	//comment
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		if (item.getItemId() == R.id.add) {

			Double totalPercentage = 0.0;
			for (GradePercentage gp : listGradePercentage) {
				totalPercentage += gp.getPercentage();
			}
			Intent intent = new Intent(this, WheelGradePercentageActivity.class);
			intent.putExtra(MISSING_PERCENTAGE, 100.0 - totalPercentage);
			startActivityForResult(intent, GRADE_PERCENTAGE_SELECTED);
		} else if (item.getItemId() == R.id.delete_all) {
			Intent intent = new Intent(this, ConfirmDeleteAllDialog.class);

			startActivityForResult(intent, CONFIRM_DELETE);

		} else if (item.getItemId() == R.id.config) {
			Intent intent = new Intent(this, WheelGradeActivity.class);

			startActivityForResult(intent, GRADE_DESIRED);

		}
		return true;
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getSupportMenuInflater();
		inflater.inflate(R.menu.actionbar_menu, menu);
		return true;
	}

	class GradePercentageAdapter extends ArrayAdapter {
		Activity context;

		GradePercentageAdapter(Activity context) {
			super(context, R.layout.linearlayout_grade, listGradePercentage);
			this.context = context;
		}

		public View getView(int position, View convertView, ViewGroup parent) {
			LayoutInflater inflater = context.getLayoutInflater();
			View item = inflater.inflate(R.layout.linearlayout_grade, null);

			TextView lblGrade = (TextView) item.findViewById(R.id.Lbl_grade);
			lblGrade.setText(Double.toString(listGradePercentage.get(position)
					.getGrade()));

			TextView lblPercentage = (TextView) item
					.findViewById(R.id.Lbl_percentage);
			lblPercentage.setText(Double.toString(listGradePercentage.get(
					position).getPercentage())
					+ "%");

			return (item);
		}
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		switch (requestCode) {
		case (GRADE_PERCENTAGE_SELECTED): {
			if (resultCode == Activity.RESULT_OK) {

				String grade = data
						.getStringExtra(WheelGradePercentageActivity.GRADE_RESULT_FROM_DIALOG);
				String percentage = data
						.getStringExtra(WheelGradePercentageActivity.PERCENTAGE_RESULT_FROM_DIALOG);

				GradePercentage gradePercentage = new GradePercentage(
						Double.valueOf(grade), Double.valueOf(percentage.replace('%', ' ').trim()));
				listGradePercentage.add(gradePercentage);
				adapter.notifyDataSetChanged();
				calcutateGrade();

			}
			break;
		}
		case (GRADE_DESIRED): {
			if (resultCode == Activity.RESULT_OK) {
				String gr = data
						.getStringExtra(WheelGradeActivity.GRADE_DESIRED);
				desiredGrade = Double.valueOf(gr);
				calcutateGrade();
			}
			break;
		}
		case (CONFIRM_DELETE): {
			if (resultCode == Activity.RESULT_OK) {
				Boolean gr = data
						.getBooleanExtra(ConfirmDeleteAllDialog.CONFIRM_DELETE,false);
				if(gr){
					listGradePercentage.clear();
					adapter.notifyDataSetChanged();
					calcutateGrade();
				}

				
			}
			break;
		}
		}
	}
}
